<!--
 * @Description:: 请补充填写
 * @Version: 1.0
 * @Author: 小白
 * @Date: 2025-10-22 09:52:30
 * @LastEditors: 小白
 * @LastEditTime: 2025-10-24 17:11:31
 * @FilePath: \tmsadmin\src\views\contract\staff\components\modals.vue
-->
<template>
  <el-dialog v-model="dialogVisible" :title="title" width="500px" :append-to-body="true" :before-close="handleClose">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm" status-icon>
      <el-form-item label="选择模板" prop="templateId">
        <!-- 选择模板 -->
        <el-select v-model="ruleForm.templateId" placeholder="请选择" clearable filterable @change="handleChange">
          <el-option v-for="item in templateList" :key="item.id" :label="item.templateName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <!-- style="position: fixed;top: 10000px;left: 10000px;z-index: 999999;" -->
    <div id="imageWrapper" ref="imageWrapper" style="position: fixed;top: 10000px;left: 10000px;z-index: 999999;">

    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCloses(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="submit(ruleFormRef)">
          确 认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { REQUEST } from '@/api/request'
import { htmlPdf } from "@/utils/htmlToPDF.js"
import HTTP_URI from '@/api/base_url'
import axios from 'axios'
import { store } from '@/store'
const ruleFormRef = ref<FormInstance>()
const title = ref('')
const dialogVisible = ref(false)
const emits = defineEmits(['ok'])
const ruleForm = ref({
  staffList: [],
  templateId: '',//模板id
  url: '',//
})

const templateList = ref([])
const rules = ref({
  templateId: [{ required: true, message: '请选择模板', trigger: 'change' }],
})
const imageUrl = ref('')
// const imageUrl = ref('https://img.kpsd56.com/20251022/1761101680932.png')

const openModal = (t: any, data: any, e: any) => {
  REQUEST.POST('TEMPLATEINFOLIST', {
    houseId: store.state.userInfo.houseId
  }).then((res: any) => {
    if (res.status === 200) {
      templateList.value = res.data
    }
  })

  REQUEST.POST('OFFICIALINFO', {
    id: store.state.userInfo.houseId
  }).then((res: any) => {
    if (res.status == 200) {
      imageUrl.value = res.data.officialSeal
      // convertImageToBase64(res.data.officialSeal, (base64: any) => {
      //   console.log(base64, '00000000000')
      // })
      fetchImage(res.data.officialSeal)
    }
  })
  ruleForm.value.staffList = data

  dialogVisible.value = true
  title.value = t
}
const fetchImage=async (url:any)=> {
  
  try {
    console.log(url,'0000201')

    const response = await fetch(url);
    console.log(response,'0000202')
    const blob = await response.blob();
    const downloadUrl = URL.createObjectURL(blob);
    
    console.log(downloadUrl,'000000000000')
     
    URL.revokeObjectURL(downloadUrl); // 释放内存
  } catch (error) {
    console.error('下载失败:', error);
  }
}
const convertImageToBase64 = (url: any, callback: any) => {
  const img = new Image();
  img.crossOrigin = 'Anonymous'; // 如果图片跨域，需要设置这个属性
  img.onload = () => {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    // 设置canvas的宽高与图片相同
    canvas.width = img.width;
    canvas.height = img.height;

    // 将图片绘制到canvas上
    ctx.drawImage(img, 0, 0);

    // 获取base64编码的字符串
    const dataUrl = canvas.toDataURL('image/png'); // 可以根据需要更改格式为'image/jpeg'等
    callback(dataUrl);
  };
  img.src = url; // 设置图片源地址
}
const textArr = ref([])
const hetongList = ref([])
const handleChange = (val: any) => {
  const content = templateList.value.filter((item: any) => item.id === val)[0].template
  REQUEST.POST('TEMPLATEINFO', {
    templateId: val,
    houseId: store.state.userInfo.houseId,
    generatorNum: ruleForm.value.staffList.length
  }).then((res: any) => {
    hetongList.value = res.data
    textArr.value = []
    ruleForm.value.staffList.map((item, index) => {
      let strs = ''
      strs = content.replaceAll('{{contractNo}}', hetongList.value[index])
      strs = strs.replaceAll('{{staff}}', item.staff)
      strs = strs.replaceAll('{{phone}}', item.phone)
      strs = strs.replaceAll('{{postalAccount}}', item.postalAccount)
      strs = strs.replaceAll('{{accountName}}', item.accountName)
      strs = strs.replaceAll('{{carOwner}}', item.carOwner)
      strs = strs.replaceAll('{{address}}', item.address)
      strs = strs.replaceAll('{{idNumber}}', item.idNumber)
      strs = strs.replaceAll('{{vehicleNumber}}', item.vehicleNumber)
      strs = strs.replaceAll('{{vehicleCommander}}', item.vehicleCommander)
      strs = strs.replaceAll('{{img}}', `<img src="${imageUrl.value}" alt="logo" style="position:absolute;bottom:150px;left:120px; width: 100px;height: 101px;"></img>`)

      const div:any = document.getElementById('imageWrapper')
      let divnew = document.createElement('div')
      divnew.innerHTML = strs
      console.log(strs,'001')
      console.log(divnew.innerHTML,'0000000002282828282')
      divnew.setAttribute('id', 'pdf' + index)
      // divnew 添加style 样式
      // divnew.style.position = 'relative'
      // 新增img 标签
      // let img = document.createElement('img')
      // img.setAttribute('src', imageUrl.value)
      // img.setAttribute('alt', 'logo')
      // img.style.position = 'absolute'
      // img.style.bottom = '300px'
      // img.style.left = '150px'
      // img.style.width = '100px'
      // img.style.height = '100px'
      // divnew.appendChild(img)
      div.appendChild(divnew)
      textArr.value.push(strs)
      console.log(textArr.value,'0000')
      // handleExport('pdf' + index, hetongList.value[index])
      // 生成图片
    })
  })


}
const handleExport = (e: any, name: any) => {
  console.log(name)
  var fileName = name + '合同';
  const fileList = document.getElementsByClassName(e)   // 很重要
  htmlPdf(fileName, document.querySelector('#' + e), fileList)
}

const handleClose = () => {
  dialogVisible.value = false
  emits('ok')
}
const handleCloses = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  emits('ok')
  dialogVisible.value = false
}
const getnowTime = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  return `${year}${month}${day}`
}
const lists = ref([])
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      lists.value = []
      let objs = {
      }
      ruleForm.value.staffList.map((item, index) => {
        objs = {
          // contractUrl: `${HTTP_URI.IMAGE_URL}/${getnowTime()}/${hetongList.value[index]}合同.pdf`,
          contractUrl:textArr.value[index],
          userId: item.userId,
          templateId: ruleForm.value.templateId,
          houseId: store.state.userInfo.houseId,
          contractNo: hetongList.value[index]
        }
        lists.value.push(objs)
      })
      REQUEST.POST('CONTRACT', {
        list: lists.value
      }).then((res: any) => {
        if (res.status === 200) {
          ElMessage({
            type: 'success',
            message: '操作成功！'
          })
          dialogVisible.value = false
          formEl.resetFields()
          emits('ok')
        } else {
          ElMessage({
            type: 'warning',
            message: res.message
          })
        }
      })

    }
  })
}
defineExpose({ openModal })
</script>

<style lang="" scoped></style>
